package com.imachen.ymcc.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.imachen.ymcc.domain.CourseMarket;
import com.imachen.ymcc.domain.CourseUserLearn;
import com.imachen.ymcc.dto.PayExtParamDto;
import com.imachen.ymcc.enums.GlobalExceptionCode;
import com.imachen.ymcc.mapper.CourseUserLearnMapper;
import com.imachen.ymcc.service.ICourseMarketService;
import com.imachen.ymcc.service.ICourseUserLearnService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.imachen.ymcc.util.AssertUtil;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author imachen
 * @since 2022-09-30
 */
@Service
public class CourseUserLearnServiceImpl extends ServiceImpl<CourseUserLearnMapper, CourseUserLearn> implements ICourseUserLearnService {

    @Autowired
    private ICourseMarketService courseMarketService;


    @Override
    public CourseUserLearn selectUserById(Long courseId, Long loginId) {
        Wrapper<CourseUserLearn> wrapper = new EntityWrapper<>();
        wrapper.eq("course_id",courseId);
        wrapper.eq("login_id",loginId);
        return selectOne(wrapper);
    }


    /**
     * 保存或修改用户课程关系
     * @param payExtParamDto
     */
    @Override
    public void saveCourseUserLearn(PayExtParamDto payExtParamDto) {
        String courseIds = payExtParamDto.getCourseIds();
        String orderNo = payExtParamDto.getOrderNo();
        Long userId = payExtParamDto.getUserId();
        // 参数校验
        AssertUtil.isNotEmpty(courseIds, GlobalExceptionCode.ERROR);
        AssertUtil.isNotEmpty(orderNo, GlobalExceptionCode.ERROR);
        AssertUtil.isNotNull(userId, GlobalExceptionCode.ERROR);
        // 将courseId转为list集合
        String[] ids = courseIds.split(",");
        List<Long> courseIdList = Arrays.stream(ids).map(id -> Long.valueOf(id)).collect(Collectors.toList());

        // 根据userId查询所有该用户的课程信息
        List<CourseUserLearn> courseUserLearns = selectList(new EntityWrapper<CourseUserLearn>().eq("login_id", userId));

        // 用map集合来接收指定课程信息
        Map<Long, CourseUserLearn> courseUserLearnMap = null;

        if (courseUserLearns != null && courseUserLearns.size() >0 ) {
            // 该用户购买过课程
            courseUserLearnMap = courseUserLearns.stream().collect(Collectors.toMap(CourseUserLearn::getCourseId, courseUserLearn -> courseUserLearn));
        }else {
            // 没有购买过课程
            courseUserLearnMap = new HashMap<>();
        }

        // 查询课程可以观看的天数信息，并转成map
        Map<Long, CourseMarket> courseMarketMap = courseMarketService.selectBatchIds(courseIdList).stream().collect(Collectors.toMap(CourseMarket::getId, courseMarket -> courseMarket));

        Date date = new Date();
        for (Long courseId : courseIdList) {
            CourseUserLearn courseUserLearn = courseUserLearnMap.get(courseId);
            CourseMarket courseMarket = courseMarketMap.get(courseId);
            Integer validDays = courseMarket.getValidDays();

            if (courseUserLearn == null ) {
                // 该用户从来没有购买过课程
                courseUserLearn = new CourseUserLearn();
                courseUserLearn.setLoginId(userId);
                courseUserLearn.setCourseId(courseId);
                courseUserLearn.setCreateTime(date);
                courseUserLearn.setCourseOrderNo(orderNo);
                courseUserLearn.setState(CourseUserLearn.YES_STATE);
                courseUserLearn.setStartTime(date);
                courseUserLearn.setEndTime(DateUtils.addDays(date,validDays));
                insert(courseUserLearn);
            }else { // 该用户购买过课程
                if (courseUserLearn.getState().equals(CourseUserLearn.NO_STATE)) {
                    // 1.过期了
                    courseUserLearn.setCourseOrderNo(orderNo);
                    courseUserLearn.setState(CourseUserLearn.YES_STATE);
                    courseUserLearn.setStartTime(date);
                    courseUserLearn.setEndTime(DateUtils.addDays(date, validDays));
                }else {
                    // 2.没过期进行续费-加时间
                    courseUserLearn.setCourseOrderNo(orderNo);
                    courseUserLearn.setEndTime(DateUtils.addDays(courseUserLearn.getEndTime(),validDays));
                }
                updateById(courseUserLearn);
            }
        }



    }
}
